package com.shao.commons.exception;

import com.shao.commons.domain.Codes;
import com.shao.commons.domain.R;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalException {

    /**
     * 处理全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R globalExceptionHandler(Exception e) {
        e.printStackTrace();
        return R.fail(Codes.FAIL);
    }

    /**
     * 处理自定义的异常
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public R serviceExceptionHandler(ServiceException e) {
        return R.fail(e.getCodes());
    }

    /**
     * 对象参数校验
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R paramsBindException(MethodArgumentNotValidException e) {
        List<String> errorList = e.getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .toList();
        return R.fail(Codes.PARAMS_BIND, errorList);
    }

    /**
     * 形参校验
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R paramsBindException(ConstraintViolationException e) {
        List<String> list = e.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .toList();
        return R.fail(Codes.PARAMS_BIND, list);
    }
}
